// coding     :utf-8
// @FileName  :WEBGIS/script.js
// @Time      :2024/02/14
// @Author    :Mingce Zhao

//-------------------------串口中全局变量----------------------
var x_ac;
var y_ac;
var z_ac;
var x_ang;
var y_ang;
var z_ang;
var x_mag;
var y_mag;
var z_mag;
var x_angle;
var y_angle;
var z_angle;
var x_qua;
var y_qua;
var z_qua;

//-------------串口发------------
function sendMessageToAndroid_S3() {
    var value_S3 = document.getElementById("contacts_S3").value;
    // 调用Android的方法并传递消息
    if (window.android) {
        window.android.receiveMessageFromS3(value_S3);
    } else {
        windows.print()("请稍后再试（安卓底层交互问题S3）");
    }
}

function sendMessageToAndroid_S5() {
    var value_S5 = document.getElementById("contacts_S5").value;

    return new Promise(function (resolve, reject) {
        if (window.android) {
            // 发送当前value_S5值
            window.android.receiveMessageFromS5(value_S5);
            // 定义要发送的指令数组
            var commands = "500300300025899F";
            function sendCommand() {
                let currentCommand = commands;
                window.android.receiveMessageFromS5(currentCommand);
            }
            setInterval(sendCommand, 1000);
        } else {
            console.log("请稍后再试（安卓底层交互问题S5）");
            reject("安卓底层交互问题");
        }
    });   //发送

}

function sendMessageToAndroid_S6() {
    var value_S6 = document.getElementById("contacts_S6").value;

    // 检查是否可以访问Android接口
    if (window.android) {
        // 发送当前的value_S6值
        window.android.receiveMessageFromS6(value_S6);

        // 定义第一个消息的命令字符串
        var command1 = "070400000010F1A0";
        var command2 = "080305DC000C8460";

        //080304B000018444读取流量   08 03 02 00 00 64 45; 08 03 02 02 37 24 F3   *0.1为真频率值08 03 05 DC 00 06 04 67,,08 03 05 DC 00 0C 84 60
        //[19:14:54.352]读取AO成功
        //[19:14:55.091]发→08 03 05 DC 00 0C 84 60
        //[19:14:55.100]收←08 03 18 43 DC A7 34 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 93 E6
        // 发送第一个命令的函数
        function sendCommand1() {
            window.android.receiveMessageFromS6(command1);
        }

        function sendCommand2() {
            window.android.receiveMessageFromS6(command2);
        }

        // 每1000ms（1秒）发送第一个命令
        setInterval(sendCommand1, 1000);
        setInterval(sendCommand2, 1500);


    } else {
        // 如果无法访问Android接口，则提供后备选项
        window.alert("请稍后再试（安卓底层交互问题S6）");
    }
}

//---------------------- 串口收 ------------------------
// -----------------模拟数据发送---------------
function simulateDataSending() {

    // 生成0到1之间的随机数
    var random = Math.random();
    // 将随机数乘以范围，并加上起始值
    var randomDecimal = ((random * 0.000999999) + 0.000009000 + 116.281573671).toFixed(9);//纬度
    var randomDecimalx = ((random * 0.000999999) + 0.000090000 + 39.941870042).toFixed(9);//经度
    var randomDecimalh = ((random * 100) + 0 + 257.144).toFixed(9);//航向角
    var randomDecimals = ((random * 10) + 0.08).toFixed(9);//地速
    // 模拟从Android接收到的数据
    var simulatedData_S3 = "$GPYBM,SN10014311,075031.00," + randomDecimalx + "," + randomDecimal + ",40.938," + randomDecimalh + ",-13.835,0.003,0.008,-0.001," + randomDecimals + ",4429701.220,182160.558,,,1,4,22,99,,0.489,18,*53";

    // 调用处理数据的函数
    getFromAndroid_S3(simulatedData_S3);
}

// 定时发送模拟数据，每隔一段时间发送一次
setInterval(simulateDataSending, 1000); // 每隔1秒发送一次数据



var data_S3d;
function getFromAndroid_S3(data_S3) {
    var processedData_S3 = data_S3;
    document.getElementById("result_S3").innerHTML = processedData_S3;
    //<!--      document.write("Received data from Android S3:", data_S3);-->
    // Handle the received data as needed
    data_S3d = processedData_S3;
}



function getFromAndroid_S5(data_S5) {
    var processedData_S5 = data_S5;
    document.getElementById("result_S5").innerHTML = processedData_S5;
    //<!--      document.write("Received data from Android S5:", data_S5);-->
    // Handle the received data as needed
    console.log(processedData_S5);

    let newArray = processedData_S5.split("·");

    var year = newArray[0];
    var month = newArray[1];
    var day = newArray[2];
    var hour = newArray[3];
    var minute = newArray[4];
    var second = newArray[5];
    var haoSecond = newArray[6];
    var acceleration = newArray[7];
    var angularVelocity = newArray[8];
    var magneticField = newArray[9];
    var angle = newArray[10];
    var quaternion = newArray[11];

    const regex = /-?\d+\.\d+/g;
    const numbers_acceleration = acceleration.match(regex).map(Number);
    x_ac = numbers_acceleration[0];
    y_ac = numbers_acceleration[1];
    z_ac = numbers_acceleration[2];
    console.log("aaaaaaa" + x_ac);

    const numbers_angularVelocity = angularVelocity.match(regex).map(Number);
    x_ang = numbers_angularVelocity[0];
    y_ang = numbers_angularVelocity[1];
    z_ang = numbers_angularVelocity[2];

    const numbers_magneticField = magneticField.match(regex).map(Number);
    x_mag = numbers_magneticField[0];
    y_mag = numbers_magneticField[1];
    z_mag = numbers_magneticField[2];

    const numbers_angle = angle.match(regex).map(Number);
    x_angle = numbers_angle[0];
    y_angle = numbers_angle[1];
    z_angle = numbers_angle[2];

    const numbers_quaternion = quaternion.match(regex).map(Number);
    z_qua = numbers_quaternion[0];
    x_qua = numbers_quaternion[1];//(rao)
    y_qua = numbers_quaternion[2];//(-)

    console.log(y_ac);
    console.log(z_ac);
    console.log(x_ang);
    console.log(y_ang);
    console.log(z_ang);
    console.log(x_mag);
    console.log(y_mag);
    console.log(z_mag);
    console.log(x_angle);
    console.log(y_angle);
    console.log(z_angle);
    console.log(x_qua);
    console.log(y_qua);
    console.log(z_qua);

    document.getElementById("result_S5x").innerHTML = newArray[0];
    document.getElementById("result_S5c").innerHTML = newArray[1];
    document.getElementById("result_S5v").innerHTML = newArray[2];
    document.getElementById("result_S5b").innerHTML = newArray[3];
    document.getElementById("result_S5n").innerHTML = newArray[4];
    document.getElementById("result_S5m").innerHTML = newArray[6];
    //document.getElementById("result_S5").innerHTML = newArray[7];
    //document.getElementById("result_S5").innerHTML = newArray[8];
    //document.getElementById("result_S5x").innerHTML = newArray[9];
    //document.getElementById("result_S5x").innerHTML = newArray[10];
    //document.getElementById("result_S5x").innerHTML = newArray[11];
    //document.getElementById("result_S5x").innerHTML = newArray[12];
    document.getElementById('x_ac').innerHTML = x_ac.toFixed(2);
    document.getElementById('y_ac').innerHTML = y_ac.toFixed(2);
    document.getElementById('z_ac').innerHTML = z_ac.toFixed(2);
    document.getElementById('x_ang').innerHTML = x_ang.toFixed(2);
    document.getElementById('y_ang').innerHTML = y_ang.toFixed(2);
    document.getElementById('z_ang').innerHTML = z_ang.toFixed(2);
    document.getElementById('x_mag').innerHTML = x_mag.toFixed(2);
    document.getElementById('y_mag').innerHTML = y_mag.toFixed(2);
    document.getElementById('z_mag').innerHTML = z_mag.toFixed(2);
    document.getElementById('x_angle').innerHTML = x_angle.toFixed(2);
    document.getElementById('y_angle').innerHTML = y_angle.toFixed(2);
    document.getElementById('z_angle').innerHTML = z_angle.toFixed(2);
    document.getElementById('x_qua').innerHTML = z_mag.toFixed(2);
    document.getElementById('y_qua').innerHTML = z_mag.toFixed(2);
    document.getElementById('z_qua').innerHTML = z_mag.toFixed(2);
}


//    function getFromAndroid_S6(data_S6) {
//      var processedData_S6 = data_S6;
//      document.getElementById("result_S6").innerHTML = processedData_S6;
//<!--      document.write("Received data from Android S6:", data_S6);-->
//      // Handle the received data as needed
//
//    }
//--------------------------------------------S6测试-----------------------
function hexToDecimalFloat(hexString) {
    // Parse the hex string to a binary string
    let binaryString = parseInt(hexString, 16).toString(2).padStart(32, '0');

    // Extract the sign, exponent, and mantissa from the binary string
    const sign = binaryString.charAt(0) === '1' ? -1 : 1;
    const exponent = parseInt(binaryString.substr(1, 8), 2) - 127;
    const mantissaBinary = '1' + binaryString.substr(9); // Add the implicit leading 1

    // Calculate the mantissa from the binary
    let mantissa = 0;
    for (let i = 0; i < mantissaBinary.length; i++) {
        mantissa += parseInt(mantissaBinary.charAt(i)) * Math.pow(2, -i);
    }

    // Calculate the final float value
    const floatValue = sign * mantissa * Math.pow(2, exponent);

    return floatValue;
}
function getFromAndroid_S6(data_S6) {
    // 定义存放结果的数组
    var resultArray = [];

    // 定义需要查找的字符串
    var searchString = "070420";

    // 找到字符串的起始位置
    var startIndex = data_S6.indexOf(searchString);

    // 如果找到了字符串
    if (startIndex !== -1) {
        // 提取从起始位置开始的72个字符
        var extractedString = data_S6.substring(startIndex, startIndex + 72);

        // 将提取的字符串每两个字符分割并存入数组
        for (var i = 0; i < extractedString.length; i += 2) {
            resultArray.push(extractedString.substring(i, i + 2));
        }

        var qiufa1 = resultArray[3];
        var qiufa2 = resultArray[4];
        var aPressure1 = resultArray[5];
        var aPressure2 = resultArray[6];
        var bPressure1 = resultArray[7];
        var bPressure2 = resultArray[8];

        // 将字符串拼接
        var qiufa = qiufa1 + qiufa2;
        var aPressure = aPressure1 + aPressure2;
        var bPressure = bPressure1 + bPressure2;

        // 从16进制转换为10进制
        var qiufaDecimal = (parseInt(qiufa, 16) - 4000) / (20000 - 4000) * 100;
        var aPressureDecimal = ((parseInt(aPressure, 16) / 1000) - 4) * (1 / 4);
        var bPressureDecimal = ((parseInt(bPressure, 16) / 1000) - 4) * (1 / 4);

        console.log("球阀开度: " + qiufaDecimal + "%");
        console.log("A压力值: " + aPressureDecimal + "mpa");
        console.log("B压力值: " + bPressureDecimal + "mpa");

        document.getElementById('value_du').textContent = qiufaDecimal.toFixed(2);
        document.getElementById('value_pressure1').textContent = aPressureDecimal.toFixed(2);
        document.getElementById('value_pressure2').textContent = bPressureDecimal.toFixed(2);

        // 在页面上显示结果（可选）

        //07 10 01 90 00 01 02 0F A0 85 E8
        //07 10 01 90 00 01 02 4E 20 B4 18
        //07 10 01 90 00 01 02 27 10 9A 5C
        document.getElementById("result_S6").innerHTML = resultArray;

    } else {
        // 如果没有找到字符串，则在页面上显示错误信息
        document.getElementById("result_S6").innerHTML = "字符串 '070420' 未找到.";
    }
    //--------------------------------------------------流量--------------------------------------------------
    // 定义存放结果的数组
    var resultArray2 = [];//流量

    // 定义需要查找的字符串
    var searchString2 = "080318";

    // 找到字符串的起始位置
    var startIndex2 = data_S6.indexOf(searchString2);

    // 如果找到了字符串
    if (startIndex2 !== -1) {
        // 提取从起始位置开始的58个字符
        var extractedString2 = data_S6.substring(startIndex2, startIndex2 + 58);

        // 将提取的字符串每四个字符分割并存入数组
        for (var i = 0; i < extractedString2.length; i += 2) {
            resultArray2.push(extractedString2.substring(i, i + 2));
        }

        var liuliang1 = resultArray2[3] + resultArray2[4];
        var liuliang2 = resultArray2[5] + resultArray2[6];
        console.log("777777777777" + liuliang1);

        // 将字符串拼接
        var liuliang = liuliang1 + liuliang2;


        const decimalFloat = hexToDecimalFloat(liuliang);
        console.log("5555555555555555555555" + decimalFloat);
        var flow = ((decimalFloat + 10) / 108);
        document.getElementById('value_flow').textContent = flow.toFixed(3);



    } else {
        // 如果没有找到字符串，则在页面上显示错误信息
        //document.getElementById("result_S6").innerHTML = "字符串 '070420' 未找到.";
    }
    // 可以根据需要处理resultArray
    // ...

    return resultArray;  // 返回结果数组
}


//------------------左侧面板收缩------------------
const toggleButton = document.getElementById('toggleButton');
toggleButton.addEventListener('click', function () {
    const leftPanel = document.querySelector('.left-panel');
    leftPanel.classList.toggle('collapsed');
    toggleButton.classList.toggle('rotated');
});

// ------------------功能列表菜单切换------------------
$(function () {
    $(".function_all").on("click", "li", function () {
        var sId = $(this).attr("id"); //获取data-id的值
        console.log(sId)
        $('#' + sId + 'Panel').removeClass('hide')
        $('#' + sId + 'Panel').siblings().addClass('hide')
    });
});

// ------------------------------------地图------------------------------------------------
var mapOptions = {
    center: [+39.943816759590774, +116.27661216853765],
    zoom: 5
}
// 在 "map" div上初始化地图
var map = L.map('map', mapOptions);

// 添加Mapbox 卫星街道作为瓦片图层
//L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
//    attribution: '地图数据 &copy; <a href="https://www.mapbox.com/">Mapbox</a>',
//    maxZoom: 23,
//    id: 'satellite-streets-v11', // 更正后的Mapbox样式 'id' 参数
//    tileSize: 512,
//    zoomOffset: -1,
//    accessToken: 'pk.eyJ1IjoiZWdnMzY1IiwiYSI6ImNscTdvN3B3bDB0eXIya3A3NWhoYnJhd2gifQ.-JKqIgzJlA8gZ7cZ4i8u2A' // 用你的Mapbox访问令牌替换
//}).addTo(map);

// 添加谷歌 卫星街道作为瓦片图层
L.tileLayer('https://gac-geo.googlecnapps.cn/maps/vt?lyrs=s&x={x}&y={y}&z={z}', {
    attribution: '地图数据 &copy; <a href="https://www.mapbox.com/">Mapbox</a>',
    maxZoom: 23,
}).addTo(map);
// 添加天地图矢量注记图层
L.tileLayer('https://t0.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=cia&STYLE=default&FORMAT=tiles&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=4267820f43926eaf808d61dc07269beb', {
    attribution: '矢量注记数据 &copy; <a href="http://www.tianditu.gov.cn/">天地图</a>',
    maxZoom: 20, // 根据天地图的实际缩放级别进行调整
}).addTo(map);

// 创建面板，并设置更高的z-index
map.createPane('topPane');
map.getPane('topPane').style.zIndex = 650; // 叠加层默认的z-index是400

//----------------------------------------串口数据解析---------------------------------------------

var processedGeojsonData;//处方图数据初始化
var latitude, longitude, heading, vel_G, north_Distance, east_Distance;//纬度，经度，航向角。。。
var marker = null; // 全局初始化标记变量
var path = []; // 初始化路径数组
var pathLine; // 用于地图上显示的路径线
var isRecordingPath = false; // 路径记录开关
var isLocationEnabled = false; // 默认情况下，位置检索是关闭的
var isCurveEnabled = false; // 默认情况下，curve显示是关闭的
var curve = L.polyline([], { color: 'red', pane: 'topPane' }).addTo(map);
var line = L.polyline([], { color: 'yellow' }).addTo(map);// 初始化线段
//21路喷头坐标
var point01, point02, point3, point4, point5, point6, point7, point8, point9, point10, point11, point12, point13, point14, point15, point16, point17, point18, point19, point20, point21;
// 定义21个变量来存储每个点对应的NUMPOINTS值
var numPointsValue1, numPointsValue2, numPointsValue3, numPointsValue4, numPointsValue5,
    numPointsValue6, numPointsValue7, numPointsValue8, numPointsValue9, numPointsValue10,
    numPointsValue11, numPointsValue12, numPointsValue13, numPointsValue14, numPointsValue15,
    numPointsValue16, numPointsValue17, numPointsValue18, numPointsValue19, numPointsValue20,
    numPointsValue21;
var numPointsValues =[];



//-------------------------------S3收到串口处理方法-------------------------------------
function processData() {
    if (isLocationEnabled) {
        if (typeof data_S3d !== 'undefined') {
            var gpx_data = data_S3d;
            var values = gpx_data.split(",");

            console.log("ccccc" + x_ac);//--------------isLocationEnabled要开启，全局变量生效--------------------
            // ------更新全局变量，获取串口值------
            latitude = parseFloat(values[3]);
            longitude = parseFloat(values[4]);
            heading = parseFloat(values[6]);
            vel_G = parseFloat(values[11]);//地速
            north_Distance = parseFloat(values[14]);
            east_Distance = parseFloat(values[15]);

            //获取原始经纬度
            var origin = turf.point([longitude, latitude]);
            console.log("origin" + origin);

            // ------更新路径数组------
            path.push([latitude, longitude]);
            console.log('Latitude:', latitude, 'Longitude:', longitude);

            // ------定位标记样式获取------
            if (marker === null) {
                // ----如果不存在，则创建标记----
                const myIcon = L.icon({
                    iconSize: [50, 50],
                    iconAnchor: [25, 25],
                    popupAnchor: [1, -34],
                    iconUrl: "../img/leaf-green.png"
                });
                marker = L.marker([latitude, longitude], { icon: myIcon, rotationOrigin: "center center" }).addTo(map);
            }
            // ----更新标记的位置和旋转角度----
            marker.setLatLng([latitude, longitude]);
            marker.setRotationAngle(heading);

            //------路径曲线------
            if (isCurveEnabled) {
                // 初始化路径Polyline，并添加到地图上
                if (curve == null) {
                    curve = new L.polyline([], { color: 'red' }).addTo(map).bringToFront();//？？？？？？？？？？？？？？？？？？？？？？？？？？将路径放在
                }
                var latlng = L.latLng(latitude, longitude);
                curve.addLatLng(latlng);
                console.log("1111", curve);
            } else {
                if (curve) {
                    console.log("R222");
                }
            }



            // ------测试，所在点的坐标获取，判断在处方图的位置------
            //            const pointCoordinates = [longitude, latitude]; // 这里是所在点的经纬度坐标（经度，纬度）
            //            console.log(pointCoordinates);
            //            // 检查 processedGeojsonData 是否存在并且包含features
            //            if (!processedGeojsonData || !processedGeojsonData.features) {
            //                console.log("processedGeojsonData 未定义或无特征数据，跳过处理。");
            //            }else{
            //                // 判断点是否在多边形内，并输出对应的 NUMPOINTS 值
            //                processedGeojsonData.features.forEach(feature => {
            //                    const polygon = turf.polygon(feature.geometry.coordinates);
            //                    const point = turf.point(pointCoordinates);
            //
            //                    if (turf.booleanPointInPolygon(point, polygon)) {
            //                      const numPointsValue = feature.properties.NUMPOINTS;
            //                      document.getElementById("value_origin").textContent = numPointsValue;
            //                      console.log(`点在多边形内，对应的 NUMPOINTS 值为: ${numPointsValue}`);
            //                    }
            //                });
            //            }
            // CRC 高位字节值表
            const auchCRCHi = [
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
                0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
                0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
                0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
                0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
                0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
                0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
                0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40

            ];

            // CRC 低位字节值表
            const auchCRCLo = [
                0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
                0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
                0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
                0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
                0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
                0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
                0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
                0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
                0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
                0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
                0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
                0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
                0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
                0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
                0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
                0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
                0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
                0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
                0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
                0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
                0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
                0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
                0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
                0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
                0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
                0x43, 0x83, 0x41, 0x81, 0x80, 0x40

            ];

            function crc16(puchMsg, usDataLen) {
                let uchCRCHi = 0xFF; // 高CRC字节初始化
                let uchCRCLo = 0xFF; // 低CRC字节初始化
                let uIndex; // CRC循环中的索引

                for (let i = 0; i < usDataLen; i++) {
                    uIndex = uchCRCHi ^ puchMsg[i];
                    uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex];
                    uchCRCLo = auchCRCLo[uIndex];
                }

                return (uchCRCHi << 8) | uchCRCLo;
            }


            // 将十六进制字符串转换为字节数组
            function hexStringToByteArray(hexString) {
                let bytes = [];
                for (let i = 0; i < hexString.length; i += 2) {
                    bytes.push(parseInt(hexString.substr(i, 2), 16));
                }
                return bytes;
            }


            //------测试，喷杆位置2d模拟（俯视图）------
            //var distanceX = 0.01;  // 东西方向100米
            //var distanceY = 0.001;  // 南北方向200米

            // 获取输入框元素
            var distanceXInput = document.getElementById('distanceX');//喷杆长度
            var distanceYInput = document.getElementById('distanceY');//喷杆与机具距离
            var nozzlesInput = document.getElementById('nozzles');//喷头数
            // 获取输入框中的值
            var distanceX = parseFloat(distanceXInput.value) / 1000;
            var distanceY = parseFloat(distanceYInput.value) / 1000;
            var nozzles = parseFloat(nozzlesInput.value) - 1;//实际喷嘴数-1

            var options = { units: 'kilometers' };  // Turf需要单位，这里我们使用千米

            // 函数来平均分割线段
            function divideLineIntoSegments(start, end, segments) {
                var points = [];
                for (var i = 0; i <= segments; i++) {
                    var t = i / segments;
                    var lat = start[0] + t * (end[0] - start[0]);
                    var lng = start[1] + t * (end[1] - start[1]);
                    points.push([lat, lng]);
                }
                return points;
            }

            // 更新点和线段的函数
            var segmentPoints;
            function updatePointsAndLine(heading) {
                // 计算第一个点（东北方向）
                var point1 = turf.destination(origin, distanceY, heading, options);  // 沿着heading方向
                var point1Offset = turf.destination(point1, distanceX, heading + 90, options);  // 垂直heading方向

                // 计算第二个点（西北方向，y轴对称）
                var point2 = turf.destination(origin, distanceY, heading, options);  // 同样沿着heading方向
                var point2Offset = turf.destination(point2, distanceX, heading - 90, options);  // 垂直heading方向

                // 确定两个点的坐标
                var coordinates1 = [point1Offset.geometry.coordinates[1], point1Offset.geometry.coordinates[0]];
                var coordinates2 = [point2Offset.geometry.coordinates[1], point2Offset.geometry.coordinates[0]];
                // 更新线段坐标
                line.setLatLngs([coordinates1, coordinates2]);
                line.bringToFront();
                // 计算线段上的21个点（包括端点）
                segmentPoints = divideLineIntoSegments(coordinates1, coordinates2, nozzles);


                point01 = segmentPoints[0],
                    point02 = segmentPoints[1],
                    point3 = segmentPoints[2],
                    point4 = segmentPoints[3],
                    point5 = segmentPoints[4],
                    point6 = segmentPoints[5],
                    point7 = segmentPoints[6],
                    point8 = segmentPoints[7],
                    point9 = segmentPoints[8],
                    point10 = segmentPoints[9],
                    point11 = segmentPoints[10],
                    point12 = segmentPoints[11],
                    point13 = segmentPoints[12],
                    point14 = segmentPoints[13],
                    point15 = segmentPoints[14],
                    point16 = segmentPoints[15],
                    point17 = segmentPoints[16],
                    point18 = segmentPoints[17],
                    point19 = segmentPoints[18],
                    point20 = segmentPoints[19],
                    point21 = segmentPoints[20];

                // 现在你可以使用这21个变量来访问每个点的坐标
                // 例如，打印第一个和最后一个点的坐标
                console.log("第一个点的坐标:", point01);
                console.log("最后一个点的坐标:", point21);




                // 遍历每个点，判断是否在多边形内，并获取NUMPOINTS值
                segmentPoints.forEach((pointCoordinates, index) => {
                    if (!processedGeojsonData || !processedGeojsonData.features) {
                        console.log("processedGeojsonData 未定义或无特征数据，跳过处理。");
                    } else {
                        processedGeojsonData.features.forEach(feature => {
                            const polygon = turf.polygon(feature.geometry.coordinates);
                            const point = turf.point([pointCoordinates[1], pointCoordinates[0]]); // 注意坐标顺序，Turf.js使用[经度, 纬度]

                            if (turf.booleanPointInPolygon(point, polygon)) {
                                const numPointsValue = feature.properties.NUMPOINTS;
                                // 根据索引赋值给对应的变量
                                eval('numPointsValue' + (index + 1) + ' = numPointsValue;');
                                console.log(`点${index + 1}在多边形内，对应的NUMPOINTS值为: ${numPointsValue}`);
                            }
                        });
                    }
                });

                // 之后你可以使用这21个numPointsValue变量
                // 例如，打印第一个和最后一个点对应的NUMPOINTS值
                console.log("第一个点对应的NUMPOINTS值:", numPointsValue1);
                console.log("最后一个点对应的NUMPOINTS值:", numPointsValue21);


                numPointsValues = [numPointsValue1, numPointsValue2, numPointsValue3, numPointsValue4, numPointsValue5,
                    numPointsValue6, numPointsValue7, numPointsValue8, numPointsValue9, numPointsValue10,
                    numPointsValue11, numPointsValue12, numPointsValue13, numPointsValue14, numPointsValue15,
                    numPointsValue16, numPointsValue17, numPointsValue18, numPointsValue19, numPointsValue20, numPointsValue21];

                // 根据numPointsValue的值转换为相应的字符串
                var resultStrings = numPointsValues.map(value => {
                    // 如果value为null，直接返回"0000"
                    if (value === null) {
                        return "0000";
                    }
                    // 基于value的值进行转换
                    switch (value) {
                        case 0:
                            return "0000";
                        case 1:
                            return "000A";
                        case 2:
                            return "0014";
                        case 3:
                            return "001E";
                        case 4:
                            return "0028";
                        case 5:
                            return "0032";
                        case 6:
                            return "003C";
                        case 7:
                            return "0046";
                        case 8:
                            return "0050";
                        case 9:
                            return "005A";
                        case 10:
                            return "0064";
                        default:
                            return "0000"; // 如果没有匹配的值，可以根据需要返回一个默认字符串
                    }
                });

                // 将转换后的字符串值拼接到一起
                var concatenatedResult = resultStrings.join("");

                console.log(concatenatedResult);
                var star = "FF100020001C380001";
                var end = "0032003200320032001FFFFF";
                var hexData = star + concatenatedResult + end;

                var data = hexStringToByteArray(hexData);
                var crcResult = crc16(data, data.length);
                var rty = crcResult.toString(16).toUpperCase();

                var str = hexData + rty;
                console.log(str);

                if (vel_G > 0) {
                     window.android.receiveMessageFromS6(str);
                };

                // 清空之前的点列表
                clearPointsList();
                // 检查每个点是否在多边形内，并输出 NUMPOINTS 值
                // 遍历每个点，检查是否在多边形内，并更新列表
                segmentPoints.forEach((point, index) => {
                    checkPointInPolygons(point, index);
                    //index正常为1，2，3.。。。。。，现在是什么？？？？？？？？？？？？？？？？？？？？？？
                });
            }

            function checkPointInPolygons(point, index) {
                // 检查 processedGeojsonData 是否存在并且包含 features
                if (!processedGeojsonData || !processedGeojsonData.features) {
                    console.log("processedGeojsonData 未定义或无特征数据，跳过处理。");
                    return;
                }
                // 判断点是否在多边形内，并输出对应的 NUMPOINTS 值
                var found = false;
                processedGeojsonData.features.forEach(feature => {
                    const polygon = turf.polygon(feature.geometry.coordinates);
                    const checkPoint = turf.point([point[1], point[0]]); // 注意：Turf 需要的坐标顺序是 [经度, 纬度]

                    if (turf.booleanPointInPolygon(checkPoint, polygon)) {
                        const numPointsValue = feature.properties.NUMPOINTS;
                        console.log(`点[${point[0]}, ${point[1]}]在多边形内，对应的 NUMPOINTS 值为: ${numPointsValue}`);
                        updatePointsList(index, numPointsValue);
                        found = true;
                    }
                });
                if (!found) {
                    numPointsValue = "null";
                    updatePointsList(index, numPointsValue);
                }
            }
            //权重值更新列表
            function updatePointsList(index, numPointsValue) {
                var pointsList = document.getElementById("pointsList");
                var listItem = pointsList.children[index] || document.createElement("li");
                listItem.textContent = `点 ${index + 1}: ${numPointsValue}`;
                if (!listItem.parentNode) {
                    pointsList.appendChild(listItem);
                }


                //在这写逻辑试试

            }


            //初始化权重值列表
            function clearPointsList() {
                var pointsList = document.getElementById("pointsList");
                while (pointsList.firstChild) {
                    pointsList.removeChild(pointsList.firstChild);
                }
            }

            console.log("2222222222222" + x_ac);
            var headingDu;
            if (parseFloat(vel_G) > 1) {
                headingDu = heading;
            } else {
                headingDu = y_angle;
            };
            // ----调用函数，更新线段----
            updatePointsAndLine(headingDu);
            //----- 更新导航数据 -------
            updateNavigationData();
        }
    }
}
//------显示经纬度等数据-----------
function updateNavigationData() {
    if (latitude != null && longitude != null) {
        document.getElementById('latitude').textContent = latitude.toFixed(6);
        document.getElementById('longitude').textContent = longitude.toFixed(6);
        document.getElementById('heading').textContent = heading.toFixed(2);
        document.getElementById('vel_G').textContent = vel_G.toFixed(2);
        document.getElementById('north_Distance').textContent = north_Distance.toFixed(2);
        document.getElementById('east_Distance').textContent = east_Distance.toFixed(2);
    }
}
setInterval(processData, 1000);

//-------导航按键判断--------
document.getElementById('switch_G').addEventListener('change', function () {
    isLocationEnabled = this.checked; // this.checked 为 true 或 false
    if (isLocationEnabled) {
        console.log("位置检索已启用");
    } else {
        console.log("位置检索已禁用");
    }
});

//-------航线按键判断--------
document.getElementById('curveSwitch').addEventListener('change', function () {
    isCurveEnabled = this.checked; // this.checked 为 true 或 false
    if (isCurveEnabled) {
        console.log("Curve显示已启用");
    } else {
        console.log("Curve显示已禁用");
    }
});
//-------路径加载--------
document.getElementById('updateFileListButton').addEventListener('click', function () {
    updateFileList();
});

//-------------放入全局变量当中----------------------
var selectedFileName = null; // 用于存储选中的文件名

function updateFileList() {
    var fileListHtml = "";
    var files = JSON.parse(android.getFileListFromDownload()); // 从 Android 端获取文件列表
    files.forEach(function (file) {
        fileListHtml += "<li onclick='selectFile(\"" + file + "\")'>" + file + "</li>";
    });
    document.getElementById("fileList").innerHTML = fileListHtml;
}
function selectFile(fileName) {
    selectedFileName = fileName;
    console.log("Selected file: " + selectedFileName);
    // 可以在这里添加额外的逻辑，比如高亮显示选中的文件项
}

//-------------放入全局变量当中----------------------
var curves; // 声明在全局作用域

function loadFile(fileName) {
    var fileContent = android.loadFileToMap(fileName); // 从 Android 端加载文件内容
    if (fileContent) {
        var convertedData = JSON.parse(fileContent);
        var latlngs = convertedData.map(entry => [entry.lat, entry.lng]);

        console.log(latlngs);
        if (curves) {
            map.removeLayer(curves); // 如果curves已存在，先移除旧的图层
        }
        curves = L.polyline(latlngs, { color: 'red' }).addTo(map);
    } else {
        alert('无法加载文件: ' + fileName);
    }
}

document.getElementById('loadFileToMapButton').addEventListener('click', function () {
    if (selectedFileName) {
        loadFile(selectedFileName);
    } else {
        alert('请先选择一个路径文件！');
    }
});

//应测试全局变量保存？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？
document.getElementById('saveCurveButton').addEventListener('click', function () {
    if (curve) {
        var latlngs = curve.getLatLngs(); // 从曲线获取点
        var data = JSON.stringify(latlngs); // 转换为 JSON
        android.saveData(data); // 调用 Android 端的接口
    } else {
        alert('没有可用的曲线数据来保存。');
    }
});

//------清除路径------
document.getElementById('removeCurveButton').addEventListener('click', function () {
    if (curves) {
        map.removeLayer(curves);
        curves = null;
    }
    // 如果 curve 变量也需要清除
    if (curve) {
        map.removeLayer(curve);
        curve = null;
    }
});



// -----------------------------处方图文件输入--------------------------------
document.getElementById('geojsonFileInput').addEventListener('change', function (event) {
    console.log("111111111");
    var fileReader = new FileReader();
    fileReader.onload = function (e) {
        var geojsonData = JSON.parse(e.target.result);
        processedGeojsonData = geojsonData;
        console.log("Processed GeoJSON:", processedGeojsonData);

        //      L.geoJSON(processedGeojsonData, {
        //          onEachFeature: function (feature, layer) {
        //              // 针对每个特征的逻辑
        //          }
        //      }).addTo(map);

        geojsonLayer = L.geoJSON(geojsonData, {
            style: function (feature) {
                let fillColor;
                switch (feature.properties.NUMPOINTS) {
                    case 11.0:
                        fillColor = "#d7191c"; // 红色填充
                        break;
                    case 10.0:
                        fillColor = "#e54f35";
                        break;
                    case 9.0:
                        fillColor = "#f3854e";
                        break;
                    case 8.0:
                        fillColor = "#fdb56a";
                        break;
                    case 7.0:
                        fillColor = "#fed38c";
                        break;
                    case 6.0:
                        fillColor = "#fff0af";
                        break;
                    case 5.0:
                        fillColor = "#eff8b0"; // 红色填充
                        break;
                    case 4.0:
                        fillColor = "#ceea91"; // 红色填充
                        break;
                    case 3.0:
                        fillColor = "#aedc72"; // 红色填充
                        break;
                    case 2.0:
                        fillColor = "#80c75f"; // 红色填充
                        break;
                    case 1.0:
                        fillColor = "#4dae50"; // 红色填充
                        break;
                    case 0.0:
                        fillColor = "#1a9641"; // 蓝色填充
                        break;
                    default:
                        fillColor = "#ffffff"; // 默认白色填充
                }
                return {
                    color: "#ffffff",      // 边框颜色
                    weight: 0.5,
                    fillColor: fillColor,  // 填充颜色
                    fillOpacity: 1       // 填充不透明度
                };
            }
        });
        geojsonLayer.addTo(map);
    };
    fileReader.onerror = function () {
        console.error('Error reading the GeoJSON file');
    };
    fileReader.readAsText(event.target.files[0]);
});




//------------------------列表选择处方图文件-------------------
document.getElementById('updateGeojsonListButton').addEventListener('click', function () {
    updateGeojsonList();
});

var selectedGeojsonFileName = null; // 用于存储选中的 Geojson 文件名

function updateGeojsonList() {
    var geojsonListHtml = "";
    var geojsonFiles = JSON.parse(android.getFileListFromGeojson()); // 从 Android 端获取 Geojson 文件列表
    geojsonFiles.forEach(function (geojsonFile) {
        geojsonListHtml += "<li onclick='selectGeojsonFile(\"" + geojsonFile + "\")'>" + geojsonFile + "</li>";
    });
    document.getElementById("geojsonList").innerHTML = geojsonListHtml;
}

function selectGeojsonFile(geojsonFileName) {
    selectedGeojsonFileName = geojsonFileName;
    console.log("Selected Geojson file: " + selectedGeojsonFileName);
    // 可以在这里添加额外的逻辑，比如高亮显示选中的 Geojson 文件项
}

//-------------放入全局变量当中----------------------
var geojsonLayer; // 声明在全局作用域

function loadGeojsonFile(geojsonFileName) {
    var geojsonContent = android.loadGeojsonFile(geojsonFileName); // 从 Android 端加载 Geojson 文件内容
    if (geojsonContent) {
        var geojsonData = JSON.parse(geojsonContent);
        processedGeojsonData = geojsonData;
        if (geojsonLayer) {
            map.removeLayer(geojsonLayer); // 如果 geojsonLayer 已存在，先移除旧的图层
        }

        geojsonLayer = L.geoJSON(geojsonData, {
            style: function (feature) {
                let fillColor;
                switch (feature.properties.NUMPOINTS) {
                    case 11.0:
                        fillColor = "#d7191c"; // 红色填充
                        break;
                    case 10.0:
                        fillColor = "#e54f35";
                        break;
                    case 9.0:
                        fillColor = "#f3854e";
                        break;
                    case 8.0:
                        fillColor = "#fdb56a";
                        break;
                    case 7.0:
                        fillColor = "#fed38c";
                        break;
                    case 6.0:
                        fillColor = "#fff0af";
                        break;
                    case 5.0:
                        fillColor = "#eff8b0"; // 红色填充
                        break;
                    case 4.0:
                        fillColor = "#ceea91"; // 红色填充
                        break;
                    case 3.0:
                        fillColor = "#aedc72"; // 红色填充
                        break;
                    case 2.0:
                        fillColor = "#80c75f"; // 红色填充
                        break;
                    case 1.0:
                        fillColor = "#4dae50"; // 红色填充
                        break;
                    case 0.0:
                        fillColor = "#1a9641"; // 蓝色填充
                        break;
                    default:
                        fillColor = "#ffffff"; // 默认白色填充
                }
                return {
                    color: "#ffffff",      // 边框颜色
                    weight: 0.5,
                    fillColor: fillColor,  // 填充颜色
                    fillOpacity: 1       // 填充不透明度
                };
            }
        })
        geojsonLayer.addTo(map);
        // 可以在这里添加额外的逻辑，比如缩放地图以适应加载的 Geojson 数据
        map.fitBounds(geojsonLayer.getBounds());
    } else {
        alert('无法加载 Geojson 文件: ' + geojsonFileName);
    }
}

document.getElementById('loadGeojsonFileToMapButton').addEventListener('click', function () {
    if (selectedGeojsonFileName) {
        loadGeojsonFile(selectedGeojsonFileName);
    } else {
        alert('请先选择一个 Geojson 文件！');
    }
});

document.getElementById('remove').addEventListener('click', function () {
    //map.removeLayer(geojsonData);

    //map.removeLayer(geojsonLayer);

    geojsonLayer.remove();
    numPointsValues = null;
});


// ----获取司南导航定位按钮元素放大到当前位置----
const locateButton = document.getElementById('locate-btn');
// 定位按钮点击事件
locateButton.addEventListener('click', function () {
    // 移动地图视图到自定义的经纬度并放大
    map.setView([latitude, longitude], 18)


    //---------解析到当前位置---------
    // 使用Mapbox Geocoding API进行地理编码
    var geocodingUrl = `https://api.mapbox.com/geocoding/v5/mapbox.places/${longitude},${latitude}.json?access_token=pk.eyJ1IjoiZWdnMzY1IiwiYSI6ImNscTdvN3B3bDB0eXIya3A3NWhoYnJhd2gifQ.-JKqIgzJlA8gZ7cZ4i8u2A`;

    // 发起API请求
    fetch(geocodingUrl)
        .then(response => response.json())
        .then(data => {
            // 在此处理响应的位置数据
            if (data.features && data.features.length > 0) {
                // 取得第一个地点的名称
                var placeName = data.features[0].place_name;
                document.getElementById('on_place').textContent = placeName;
                // 输出地点名称或进行其他处理
                console.log(placeName);
            } else {
                console.log("No results found");
            }
        });

});


// Three.js 初始化
function initThreeJS() {
    console.log("qwwwwwwwwwww" + z_ac);

    // 创建场景
    const scene = new THREE.Scene();

    // 创建相机
    const camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000); // 使用1:1的宽高比
    camera.position.set(30, 0, 30);

    // 创建渲染器并添加到HTML
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(200, 200); // 调整渲染器大小
    renderer.setClearColor(0xffffff); // 设置背景颜色为白色
    document.getElementById("content_fourshu").appendChild(renderer.domElement);

    // 添加光源
    const ambientLight = new THREE.AmbientLight(0x404040); // soft white light
    scene.add(ambientLight);
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
    scene.add(directionalLight);

    // 主体
    var bodyGeometry = new THREE.BoxGeometry(3, 1, 2);
    var bodyMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
    var body = new THREE.Mesh(bodyGeometry, bodyMaterial);

    // 车顶
    var cabinGeometry = new THREE.BoxGeometry(1, 0.5, 1.5);
    var cabinMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
    var cabin = new THREE.Mesh(cabinGeometry, cabinMaterial);
    cabin.position.set(0, 0.75, 0);

    // 车轮
    var wheelGeometry = new THREE.CylinderGeometry(0.5, 0.5, 1, 32);
    var wheelMaterial = new THREE.MeshLambertMaterial({ color: 0x000000 });
    var wheelPositions = [
        { x: -1.5, y: -0.5, z: 1 },
        { x: -1.5, y: -0.5, z: -1 },
        { x: 1.5, y: -0.5, z: 1 },
        { x: 1.5, y: -0.5, z: -1 }
    ];

    var wheels = wheelPositions.map(function (pos) {
        var wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
        wheel.rotation.x = Math.PI / 2; // Rotate the wheel 90 degrees
        wheel.position.set(pos.x, pos.y, pos.z);
        return wheel;
    });

    // 组装拖拉机
    var tractor = new THREE.Group();
    tractor.add(body);
    tractor.add(cabin);
    wheels.forEach(function (wheel) {
        tractor.add(wheel);
    });

    // 将拖拉机置于地面之上
    tractor.position.y = 0.5;
    tractor.scale.set(9, 9, 9); // 调整模型尺寸

    // 添加到场景
    scene.add(tractor);

    // 创建喷杆的几何体和材料
    var sprayBarGeometry = new THREE.BoxGeometry(0.2, 0.2, 5); // 宽、高、长
    var sprayBarMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
    var sprayBar = new THREE.Mesh(sprayBarGeometry, sprayBarMaterial);

    // 定位喷杆在拖拉机前方
    sprayBar.position.set(2, 0.5, 0); // 调整位置以匹配拖拉机的前端

    // 将喷杆添加到拖拉机上
    tractor.add(sprayBar);

    // 创建OrbitControls
    const controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.target = tractor.position; // 设置控制的目标为拖拉机位置
    controls.update(); // 必须在设置了target之后调用

    // // 定义一个四元数表示喷杆的旋转
    // var sprayBarQuaternion = new THREE.Quaternion();

    // sprayBarQuaternion.setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI / 18); // 以Y轴为轴，旋转10度

    // // 动画循环
    // function animate() {
    //     requestAnimationFrame(animate);
    //     // 应用四元数旋转到喷杆
    //     sprayBar.quaternion.multiplyQuaternions(sprayBar.quaternion, sprayBarQuaternion);

    //     //    // 更新控制器
    //     controls.update();
    //     renderer.render(scene, camera);
    // }

    // animate(); // 启动动画循环

    console.log("wwswwwwwwwwww" + x_qua);
    // 动画循环
    //function animate() {
    //    requestAnimationFrame(animate);
    //
    //    // 创建一个新的四元数用于存储喷杆的旋转状态
    //    var sprayBarRotation = new THREE.Quaternion();
    //
    //    // 将从传感器返回的四元数值应用到喷杆的旋转状态中
    //    sprayBarRotation.multiplyQuaternions(x_qua, y_qua);
    //    sprayBarRotation.multiply(z_qua);
    //
    //    // 应用四元数旋转到喷杆
    //    sprayBar.quaternion.copy(sprayBarRotation);
    //
    //    // 更新控制器
    //    controls.update();
    //    renderer.render(scene, camera);
    //}




    // 修改喷杆方向
    function updateSprayBarOrientation(x_qua, y_qua, z_qua) {
        // 根据传感器四元数的值更新喷杆的方向
        sprayBar.setRotationFromQuaternion(new THREE.Quaternion(x_qua, y_qua, z_qua, 1));
    }

    // 在渲染循环中调用updateSprayBarOrientation函数
    function render() {
        // 更新喷杆方向
        updateSprayBarOrientation(x_qua, y_qua, z_qua);

        // 渲染场景
        renderer.render(scene, camera);

        // 循环调用render函数
        requestAnimationFrame(render);

    }
    render();

}

// 停止动画循环
function stopAnimation() {
    // 如果有需要，在这里停止动画循环
}


